package com.hy.study.utils;

import com.google.common.base.Joiner;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 列表转换成字符串
 *
 * @author huyong
 * @date 2024 年 01 月 11 日 17:17: 01
 */
public class Collection2String {
    private final List<String> list = new ArrayList<>();
    private final String split = ",";

    @Before
    public void before() {
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
    }

    @Test
    public void test() {
        // 方式一
        StringBuilder builder = new StringBuilder();
        for (String str : list) {
            builder.append(str).append(split);
        }
        System.out.println(builder.substring(0, builder.length() - 1));
        // 方式二 缺点 只能是字符串不能是int
        String join = String.join(split, list);
        System.out.println(join);
        // 方式三 可以是任何类型的数据
        String joined = Joiner.on(split).join(list);
        System.out.println(joined);
        // 方式四 不用在最后一位截取
        StringJoiner joiner = new StringJoiner(split);
        for (String str : list) {
            joiner.add(str);
        }
        System.out.println(joiner.toString());
        // 方式五 jdk8 stream
        String collect = list.stream().map(String::valueOf).collect(Collectors.joining(split));
        System.out.println(collect);

    }

    /**
     * 避免了最后的截取
     *
     * @param list
     *
     * @return
     */
    public String join2(List<Integer> list) {
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (Integer sub : list) {
            if (first) {
                first = false;
            } else {
                builder.append(",");
            }
            builder.append(sub);
        }
        return builder.toString();
    }
}


